package com.lolo.json.restlet.test;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import com.lolo.json.restlet.JsonMetaData;
import com.lolo.json.restlet.JsonServletRequestHandler;
import com.lolo.presentation.service.poc.PartnerDetailService;
import com.thoughtworks.xstream.XStream;

public class JsonArticlesHandler implements JsonServletRequestHandler {

	private String version;
	private String serviceName;
	
	@Override
	public Object executeRequest(String action, HttpServletRequest data) throws IOException {
		URL wsdlLocation = new URL("http://predic8.com:8080/material/ArticleService?wsdl");
		QName serviceQName = new QName("http://predic8.com/wsdl/material/ArticleService/1/", "ArticleService");
		Service service = Service.create(wsdlLocation, serviceQName);
		ArticleServicePT port = service.getPort(ArticleServicePT.class);

		if (action.equals("list")) {
			return port.getAll();
		} else if (action.equals("get")) {
			String id = data.getParameter("id");
			return port.get(id);
		} else if (action.equals("delete")) {
			String id = data.getParameter("id");
			port.delete(id);
			return null;
		} else if (action.equals("add")) {
			String id = data.getParameter("id");
			String name = data.getParameter("name");
			String description = data.getParameter("description");
			String currency = data.getParameter("currency");
			String price = data.getParameter("price");
			
			ArticleType article = new ArticleType();
			article.setId(id);
			article.setName(name);
			article.setDescription(description);
			MoneyType moneyType = new MoneyType();
			moneyType.setCurrency(CurrencyType.fromValue(currency));
			moneyType.setAmount(new BigDecimal(price));
			article.setPrice(moneyType);
			return port.create(article);
		} else {
			throw new IOException("action "+action+" is not defined");
		}
	}

	@Override
	public void configureJsonMapping(String action, XStream xStream) throws IOException {
		xStream.omitField(ArticleService.class, "fieldToOmitInTheResponse");  
		xStream.alias("articleType", ArticleType.class);  
	}

	@Override
	public void getMetaData(JsonMetaData meta) throws IOException {
		meta.addAction("list").setDescription("lists all possible articles");
		meta.addAction("get", "id").setDescription("gets an article based on an ID");
		meta.addAction("add", "id", "name", "description", "price", "currency").setDescription("adds a new article incl price");
		meta.addAction("delete", "id").setDescription("delets an existing");
	}
	@Override
	public void setVersion(String version) {
		this.version = version;
	}

	@Override
	public String getVersion() {
		return this.version;
	}

	@Override
	public void setServiceName(String serviceName) {
		this.serviceName = serviceName;
	}

	@Override
	public String getServiceName() {
		return this.serviceName;
	}
}
